<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Controller;

use Admin\Controller\AdminActionController;
use Doctrine\ORM\EntityManager;
use Goods\Entity\Goods;
use Goods\Form\GoodsReplyEvaluationForm;
use Goods\Form\SearchGoodsEvaluationForm;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;
use Laminas\View\Model\ViewModel;
use Sales\Entity\OrderGoods;
use Sales\Entity\OrderGoodsEvaluation;
use Sales\Entity\OrderGoodsEvaluationBase;
use Sales\Service\OrderGoodsEvaluationBaseManager;
use Sales\Service\OrderGoodsEvaluationManager;
use Sales\Service\OrderGoodsManager;

class GoodsEvaluationController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $orderGoodsEvaluationManager;
    private $orderGoodsEvaluationBaseManager;
    private $orderGoodsManager;

    public function __construct(
        Translator $translator,
        EntityManager $entityManager,
        OrderGoodsEvaluationManager $orderGoodsEvaluationManager,
        OrderGoodsEvaluationBaseManager $orderGoodsEvaluationBaseManager,
        OrderGoodsManager $orderGoodsManager
    )
    {
        $this->translator   = $translator;
        $this->entityManager= $entityManager;
        $this->orderGoodsEvaluationManager = $orderGoodsEvaluationManager;
        $this->orderGoodsEvaluationBaseManager = $orderGoodsEvaluationBaseManager;
        $this->orderGoodsManager = $orderGoodsManager;
    }

    /**
     * 商品评价
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $page = (int) $this->params()->fromQuery('page', 1);

        $search = [];
        $searchForm = new SearchGoodsEvaluationForm();
        if($this->getRequest()->isGet()) {
            $data = $this->params()->fromQuery();
            $searchForm->setData($data);
            if($searchForm->isValid()) $search = $searchForm->getData();
        }

        $query = $this->entityManager->getRepository(OrderGoodsEvaluationBase::class)->findOrderGoodsEvaluationBase($search);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return ['evaluationBaseList' => $paginator, 'searchForm' => $searchForm];
    }

    /**
     * 某个商品评价
     * @return array|\Laminas\Http\Response
     */
    public function showEvaluationAction()
    {
        $page = (int) $this->params()->fromQuery('page', 1);

        $goodsId    = (int) $this->params()->fromRoute('id', -1);
        $goodsInfo  = $this->entityManager->getRepository(Goods::class)->findOneBy(['goodsId' => $goodsId]);
        if($goodsInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该商品不存在!'));
            return $this->redirect()->toRoute('goods-evaluation');
        }

        $queryData = $this->params()->fromQuery();
        $queryData['page'] = $queryData['sPage'];
        unset($queryData['sPage']);

        $query      = $this->entityManager->getRepository(OrderGoodsEvaluation::class)->findGoodsEvaluationList($goodsId);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return ['goodsInfo' => $goodsInfo, 'evaluationList' => $paginator, 'queryData' => $queryData];
    }

    /**
     * 商品评价回复
     * @return \Laminas\Http\PhpEnvironment\Response|\Laminas\Stdlib\ResponseInterface|JsonModel|ViewModel|mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function replyEvaluationAction()
    {
        $view = new ViewModel();
        $view->setTerminal(true);

        $evaluationId   = (int) $this->params()->fromRoute('id', -1);
        $evaluationInfo = $this->entityManager->getRepository(OrderGoodsEvaluation::class)->findOneBy(['evaluationId' => $evaluationId]);
        if($evaluationInfo == null) return $this->getResponse()->setContent('');

        $form = new GoodsReplyEvaluationForm();
        $form->get('evaluationShowState')->setValueOptions([1 => $this->translator->translate('前台显示'), 0 => $this->translator->translate('前台不显示')]);
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                $this->orderGoodsEvaluationManager->editEvaluation([
                    'replyBody' => $data['replyBody'],
                    'evaluationShowState' => $data['evaluationShowState'],
                    'replyTime' => time(),
                    'replyUser' => $this->translator->translate('店主')
                ], $evaluationInfo);

                $this->adminCommon()->addOperLog($this->translator->translate('商品评价回复成功!'), $this->translator->translate('商品评价'));

                return new JsonModel(['status' => 'true']);
            } else return new JsonModel(['status' => 'false', 'message' => $this->translator->translate('评价回复失败!')]);
        }

        $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneByGoodsId($evaluationInfo->getGoodsId());

        $form->setData(['evaluationShowState' => $evaluationInfo->getEvaluationShowState(), 'replyBody' => $evaluationInfo->getReplyBody()]);

        return $view->setVariables(['form' => $form, 'evaluationInfo' => $evaluationInfo, 'goodsInfo' => $goodsInfo]);
    }

    /**
     * 商品评价删除
     * @return \Laminas\Http\Response
     */
    public function deleteEvaluationAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $evaluationId   = (int) $this->params()->fromRoute('id', -1);
        $evaluationInfo = $this->entityManager->getRepository(OrderGoodsEvaluation::class)->findOneBy(['evaluationId' => $evaluationId]);
        if($evaluationInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该评价不存在!'));
            return $this->redirect()->toRoute('goods-evaluation');
        }

        $orderGoodsInfo = $this->entityManager->getRepository(OrderGoods::class)->findOneBy(['orderGoodsId' => $evaluationInfo->getOrderGoodsId()]);

        $this->entityManager->beginTransaction();
        try {
            $this->orderGoodsEvaluationManager->deleteEvaluation($evaluationInfo);
            $this->orderGoodsEvaluationBaseManager->changeOrderGoodsEvaluationBaseCount($evaluationInfo->getGoodsId());
            if($orderGoodsInfo == null) $this->orderGoodsManager->editOrderGoods(['evaluationStatus' => 0], $orderGoodsInfo);

            $this->entityManager->commit();
            $this->adminCommon()->addOperLog($this->translator->translate('商品评价删除成功!'), $this->translator->translate('商品评价'));
        } catch (\Exception $e) {
            $this->entityManager->rollback();
            $this->flashMessenger()->addWarningMessage($this->translator->translate('商品评价删除失败!'));
        }

        return $this->adminCommon()->toReferer();
    }
}